package com.basic.nio.groupchatdemo;



import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @Author: wisdom
 * @Date: 2024/4/1  9:19 PM
 * @Description:
 */
public class Client {

    /**
     * 服务器地址
     */
    private final String HOST = "127.0.0.1";
    /**
     * 服务器端口
     */
    private final int PORT = 6667;

    private Selector selector;
    private static SocketChannel socketChannel;
    private String username;

    public Client() {
        try {
            selector = Selector.open();
            // 连接服务器
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            // 设置非阻塞
            socketChannel.configureBlocking(false);
            // 将channel 注册到selector， 注册读取事件
            socketChannel.register(selector, SelectionKey.OP_READ);
            // 得到username
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username + " is ok!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        Client chatClient = new Client();
        // 启动一个线程, 每3秒，读取从服务器发送数据
        new Thread() {
            public void run() {
                while (true) {
                    chatClient.readMsg();
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        }
    }

    private void readMsg() {
        try {
            int count = selector.select();
            // 有可用的通道
            if (count > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        // 开启一个buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        channel.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }

                // 删除当前的selectionKey, 防止重复操作
                iterator.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
